package com.bckj.fastboot.upms.api.util.dict;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.bckj.fastboot.core.lang.exception.BusinessException;
import com.bckj.fastboot.upms.api.entity.SysDict;
import com.bckj.fastboot.upms.api.util.dict.annotation.Dict;

public class ExcelDictConverter implements Converter<String> {

    @Override
    public String convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        Dict[] dicts = contentProperty.getField().getDeclaredAnnotationsByType(Dict.class);
        if (dicts == null || dicts.length == 0) {
            return null;
        }
        Dict dict = dicts[0];
        return DictResolver.getByCode(dict.type(), cellData.getData().toString()).map(SysDict::getName).orElse(null);
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        Dict[] dicts = contentProperty.getField().getDeclaredAnnotationsByType(Dict.class);
        if (dicts == null || dicts.length == 0) {
            return null;
        }
        Dict dict = dicts[0];
        String code = DictResolver.getByName(dict.type(), value).map(SysDict::getCode).orElseThrow(() -> new BusinessException("转换失败，字典值" + value + "未定义"));
        return new WriteCellData<>(code);
    }


}
